﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Xml;

namespace Auction
{
    public abstract class WebPage : System.Web.UI.Page
    {

        protected static AuthorizePage AUTHORIZE_PAGE;

        protected void Page_Load(object sender, EventArgs e)
        {
            if(IsAuthorize(Request,Response))
            {
                this.LoadPage(sender, e);
            }
        }


        protected abstract void LoadPage(object sender, EventArgs e);

        public Boolean IsAuthorize(HttpRequest Request, HttpResponse Response)
        {
            if (AUTHORIZE_PAGE == null)
            {
                AUTHORIZE_PAGE = this.ParseAuthorizeXML();
            }
            if (AUTHORIZE_PAGE != null)
            {
                String roleID = "0";
                if (Session["ROLE_ID"] != null && !Session["ROLE_ID"].ToString().Equals(""))
                {
                    roleID = Session["ROLE_ID"].ToString();
                }
                Object[] list = AUTHORIZE_PAGE.Get(roleID);
                String pathCurrent = this.GetType().Name;
                if (list != null)
                {
                    Boolean isAllow = false;
                    for (int i = 0; !isAllow && i < list.Count(); i++)
                    {
                        if (list[i].Equals(pathCurrent))
                        {
                            isAllow = true;
                        }
                    }
                    return isAllow;
                }
            }
            return false;
        }

           //parse authorize.xml
        private AuthorizePage ParseAuthorizeXML() {
            AuthorizePage authPage = new AuthorizePage();
            String pathSource = Server.MapPath("~/authorize.xml");
            XmlDocument authorizeDom = new XmlDocument();
            authorizeDom.Load(pathSource);
            XmlNodeList authorizeList = authorizeDom.GetElementsByTagName("user");

            for (int i = 0; authorizeList != null && i < authorizeList.Count; i++)
            {
                String[] controllerArray = authorizeList[i].LastChild.InnerText.Split(',');
                for (int j = 0; controllerArray != null && j < controllerArray.Length; j++)
                {
                        String controller =  controllerArray[j].Replace("\n","");
                        authPage.Add(authorizeList[i].FirstChild.InnerText, controller.Trim());
                }
            }
            return authPage;
        }
    }
}
